package io.github.elkan1788.mpservice.module;

import io.swagger.annotations.*;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;

/**
 * Mock cmd options
 *
 * @author 凡梦星尘(elkan1788@gmail.com)
 */
@Api(value = "cmd", tags = {"command"})
@At("/cmd")
@IocBean(create = "init", depose = "depose")
public class CmdModule {

    private static final Log logger = Logs.get();

    public void init() {

    }

    public void depose() {

    }

    @POST
    @ApiOperation(value = "测试指定HOST的连接", notes = "模仿Linux的ping命令功能", httpMethod = "POST",
            consumes = "application/x-www-form-urlencoded", response = String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "host", value = "主机HostName或IP地址", defaultValue = "127.0.0.1", required = true,
                    paramType = "form", dataType = "string")
    })
    @At
    @Ok("raw")
    public String ping(@Param("host") String host) {
        return socketConnect(host, 80);
    }

    @POST
    @ApiOperation(value = "测试指定HOST的端口连接", notes = "模仿Linux的telnet命令功能", httpMethod = "POST",
            consumes = "application/x-www-form-urlencoded", response = String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "host", value = "主机HostName或IP地址", defaultValue = "127.0.0.1", required = true,
                    paramType = "form", dataType = "string"),
            @ApiImplicitParam(name = "port", value = "主机端口", defaultValue = "80", required = true,
                    paramType = "form", dataType = "integer")
    })
    @At
    @Ok("raw")
    public String telnet(@Param("host") String host, @Param("port") int port) {
        return socketConnect(host, port);
    }

    @POST
    @ApiOperation(value = "读取变量值", notes = "获取系统环境变量值", httpMethod = "POST",
            consumes = "application/x-www-form-urlencoded", response = String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "env", value = "环境变量名", defaultValue = "HOME", required = true,
                    paramType = "form", dataType = "string")
    })
    @At
    @Ok("raw")
    public String sysenv(@Param("env") String env) {
        String envVal = System.getenv(env);
        return env + ": " + (envVal==null ? "Not Found" : envVal);
    }


    private String socketConnect(String host, int port) {
        String resp = "";
        try {
            long start = System.currentTimeMillis();
            SocketChannel sc = SocketChannel.open(new InetSocketAddress(host, port));
            long stop = System.currentTimeMillis();
            if (sc.isConnected()) {
                resp = "Reachable [" + host + ":" + port + "]: " + Long.toString(stop - start) + "ms";
            } else {
                resp = "UnReachable [" + host + "]: " + Long.toString(stop - start) + "ms";
            }
            sc.close();
        } catch (IOException e) {
            resp = "Not reachable \"" + host + "\" !!!";
            logger.error(e);
        }

        return resp;
    }
}
